#!/bin/sh

# ctdbd wrapper - start or stop CTDB

usage ()
{
    echo "usage: ctdbd_wrapper { start | stop }"
    exit 1
}

[ $# -eq 1 ] || usage

action="$1"

############################################################

if [ -z "$CTDB_BASE" ] ; then
    export CTDB_BASE="/usr/local/etc/ctdb"
fi

. "${CTDB_BASE}/functions"

load_system_config "ctdb"

ctdbd="${CTDBD:-/usr/local/sbin/ctdbd}"

############################################################

start()
{
    eval "$ctdbd" || return 1

    # Wait until ctdbd has started and is ready to respond to clients.
    _timeout="${CTDB_STARTUP_TIMEOUT:-10}"
    _count=0
    while [ "$_count" -lt "$_timeout" ] ; do
	if $CTDB runstate first_recovery startup running >/dev/null 2>&1 ; then
	    return 0
	fi

	_count=$((_count + 1))
	sleep 1
    done

    echo "Timed out waiting for initialisation - check logs"
    # Attempt a shutdown just in case things are still running
    $CTDB shutdown >/dev/null 2>&1
    drop_all_public_ips >/dev/null 2>&1
    return 1
}

stop()
{
	$CTDB shutdown

	# The above command is important and needs to stand out, so
	# post-check exit status
	# shellcheck disable=SC2181
	if [ $? -ne 0 ] ; then
		echo "Error while shutting down CTDB"
		drop_all_public_ips >/dev/null 2>&1
		return 1
	fi

	return 0
}

############################################################

# Allow notifications for start/stop.
if [ -x "$CTDB_BASE/rc.ctdb" ] ; then
    "$CTDB_BASE/rc.ctdb" "$action"
fi

case "$action" in
    start) start ;;
    stop)  stop  ;;
    *)
	echo "usage: $0 {start|stop}"
	exit 1
esac
